import { Strategy, IStrategyOptions } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, BadRequestException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { compareSync } from 'bcryptjs';
import { loginDto } from './dto/user.dto';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
  constructor(private readonly authService: AuthService) {
    super({
      usernameField: 'username',
      passwordField: 'password'
    } as IStrategyOptions);
  }

  async validate(username: string, password: string): Promise<loginDto> {
    const user = await this.authService.validateUser(username,password);
    if (!user) {
      throw new BadRequestException('用户名或密码错误')
    }
    if(!compareSync(password,user.password)) {
      throw new BadRequestException('用户名或密码错误')
    }
    return user;
  }
}
